'use client';

import { createContext, useContext, useEffect, useState } from 'react';
import { themes } from '@/config/themes';

interface ThemeContextType {
  theme: string;
  mode: 'light' | 'dark';
  setTheme: (theme: string) => void;
  setMode: (mode: 'light' | 'dark') => void;
  toggleMode: () => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}

interface ThemeProviderProps {
  children: React.ReactNode;
  defaultTheme?: string;
  defaultMode?: 'light' | 'dark';
}

export function ThemeProvider({ 
  children, 
  defaultTheme = 'violet', 
  defaultMode = 'light' 
}: ThemeProviderProps) {
  const [theme, setThemeState] = useState(defaultTheme);
  const [mode, setModeState] = useState<'light' | 'dark'>(defaultMode);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    
    // Only access localStorage on client side
    if (typeof window !== 'undefined') {
      // Load theme from localStorage
      const savedTheme = localStorage.getItem('theme');
      const savedMode = localStorage.getItem('mode') as 'light' | 'dark';
      
      if (savedTheme && themes.find(t => t.name === savedTheme)) {
        setThemeState(savedTheme);
      }
      
      if (savedMode && (savedMode === 'light' || savedMode === 'dark')) {
        setModeState(savedMode);
      } else {
        // Check system preference
        const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        setModeState(systemPrefersDark ? 'dark' : 'light');
      }
    }
  }, []);

  useEffect(() => {
    if (!mounted || typeof window === 'undefined') return;

    const root = document.documentElement;
    const selectedTheme = themes.find(t => t.name === theme);
    
    if (selectedTheme) {
      const vars = selectedTheme.cssVars[mode];
      
      // Apply CSS variables
      Object.entries(vars).forEach(([key, value]) => {
        root.style.setProperty(`--${key}`, value);
      });
      
      // Apply theme class
      root.className = `theme-${theme}`;
      
      // Apply mode class
      if (mode === 'dark') {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
    }
    
    // Save to localStorage
    localStorage.setItem('theme', theme);
    localStorage.setItem('mode', mode);
  }, [theme, mode, mounted]);

  const setTheme = (newTheme: string) => {
    if (themes.find(t => t.name === newTheme)) {
      setThemeState(newTheme);
    }
  };

  const setMode = (newMode: 'light' | 'dark') => {
    setModeState(newMode);
  };

  const toggleMode = () => {
    setModeState(prev => prev === 'light' ? 'dark' : 'light');
  };

  // Prevent hydration mismatch by showing a loading state until mounted
  if (!mounted) {
    return (
      <ThemeContext.Provider value={{ theme, mode, setTheme, setMode, toggleMode }}>
        <div suppressHydrationWarning>{children}</div>
      </ThemeContext.Provider>
    );
  }

  return (
    <ThemeContext.Provider value={{ theme, mode, setTheme, setMode, toggleMode }}>
      {children}
    </ThemeContext.Provider>
  );
} 